<?php
namespace Usap\Service\Account;
class sms{

	public $reset_after_verifycode = true;//认证成功后自动删除

	protected $config =	array(
			'seKey'     =>  'sms',   // 验证码加密密钥
			'codeSet'   =>  '0123456789',             // 验证码字符集合
			'expire'    =>  1800,            // 验证码过期时间（s）
			'length'    =>  4,               // 验证码位数
			'reset'     =>  false,           // 验证成功后是否重置
	);
	
	
	private $link_cfg = array(
		'YunTongXun'=>array(
		),
		'WYYun'=>array(
				'AppKey'=>'860148929036161aba4e1b276d611857',
				'AppSecret'=>'de8a34d98c9d',
				'templateCfg'=>array('grantOnline'=>'3060510'),
		),
		
	);

	/**
	 * 使用 $this->name 获取配置
	 * @access public
	 * @param  string $name 配置名称
	 * @return multitype    配置值
	 */
	public function __get($name) {
		return $this->config[$name];
	}
	
	/**
	 * 设置验证码配置
	 * @access public
	 * @param  string $name 配置名称
	 * @param  string $value 配置值
	 * @return void
	 */
	public function __set($name,$value){
		if(isset($this->config[$name])) {
			$this->config[$name]    =   $value;
		}
	}
	
	/**
	 * 获取短信发送状态
	 * @param unknown $message_sid
	 */
	public function getSendStatus($message_sid){
		
		$rest = new wyyun($this->link_cfg['WYYun']['AppKey'], $this->link_cfg['WYYun']['AppSecret'] );
		return  $rest->getSendStatus($message_sid);
	}
	
	
	/**
	 * 添加短信记录
	 * @param unknown $summary
	 * @param unknown $sub_summary
	 * @param unknown $channel_name
	 * @param unknown $send_to
	 */
	public function createSmsLog($summary, $sub_summary, $channel_name, $send_to,$send_msg='',$channel_template_id='',$channel_msg_id='',$send_status=''){
		
		$data_list = array(
			'channel_name'=>$channel_name,'channel_msg_id'=>$channel_msg_id,
			'send_msg'=>$send_msg,'send_to'=>$send_to,'channel_template_id'=>$channel_template_id,
			'summary'=>$summary,'sub_summary'=>$sub_summary,
			'send_status'=>$send_status,'create_time'=>date('Y-m-d H:i:s'),
		);
		D("Usap/Account/SMSLog")->add($data_list);
	}
	
	
	/**
	 * 发送手机验证码
	 * @param string $mobile
	 * @param string $type_id
	 * @param string $expire_time过期时间
	 */
	public function sendCode($mobile,$type_id,$expire_time=''){
		
		//随机生成验证码，并存入session
		$code = $this->entry($type_id,array('mobile'=>$mobile));

		//调用协议发送验证码
		$rest = new wyyun($this->link_cfg['WYYun']['AppKey'], $this->link_cfg['WYYun']['AppSecret'] );

		$data = array($code);
		$tempId = $this->link_cfg['WYYun']['templateCfg'][$type_id];
		$result = $rest->sendTemplateSMS($mobile, $data, $tempId);
		if ($result) {
			
			$code = (String) $result->statusCode;
			
			//@TODO 后续根据不同的短信类别修改..
			$this->createSmsLog('account', 'grantonline', 'wyyun', $mobile,'', $tempId, $result->smsMessageSid, '');
			if ($code === '0000') {

				return array('code'=>'0000','msg'=>'发送成功','message_sid'=>$result->smsMessageSid);
			} else {
				return array('code'=>$code,'msg'=>(String) $result->statusMsg);
			}
		}
	} 
	
	
	/**
	 * 获取验证码接收时的手机号
	 */
	public function getVerifyMobile($code_type){
		
		$cache_key =  $this->authcode($this->seKey).'_'.$code_type;
		$cache_info = session($cache_key);
		return $cache_info['mobile'];
	}
	
	
	/**
	 * 获取验证码发送时间
	 * @param unknown $code_type
	 */
	public function getVerifyTime($code_type){
		
		$cache_key =  $this->authcode($this->seKey).'_'.$code_type;
		$cache_info = session($cache_key);
		return $cache_info['verify_time'];
	}
	
	
	/**
	 * 验证手机验证码
	 * @param string $code_type
	 * @param string $verify_code
	 */
	public function verifyCode($code_type, $verify_code){

		$cache_key = $this->authcode($this->seKey).'_'.$code_type;

		
		$cache_info = session($cache_key);
		if(empty($code_type) || empty($cache_info)) {

			return array('code'=>'PARAM_ERROR','msg'=>'存储数据为空');
		}

		if(NOW_TIME - $cache_info['verify_time'] > $this->expire) {
			session($cache_key, null);
			return array('code'=>'VERIFY_EXPIRE','msg'=>'验证码已经过期');
		}
		
		if($this->authcode(strtoupper($verify_code)) == $cache_info['verify_code']) {
			$this->reset_after_verifycode && session($cache_key, null);
			
			return array('code'=>'0000','msg'=>'校验成功');
		}
		
		return array('code'=>'VERIFY_ERROR','msg'=>'验证码有误');
		
	}
	
	
	/**
	 * 获取验证码并存入session中
	 * 验证码保存到session的格式为： array('verify_code' => '验证码值', 'verify_time' => '验证码创建时间');
	 * @access public
	 * @param string $id 要生成验证码的标识
	 * @return void
	 */
	public function entry($id, $ext_info = array()){

		$code_str = '';
		for ($i = 0; $i<$this->length; $i++) {
			$code_str[$i] = $this->codeSet[mt_rand(0, strlen($this->codeSet)-1)];
		}
		
		$cache_key =  $this->authcode($this->seKey).'_'.$id;
		$cache_list = array(
			'verify_code'=>$this->authcode(strtoupper(implode('', $code_str))),
			'verify_time'=>NOW_TIME
		);
		if(!empty($ext_info)){

			$cache_list = array_merge($cache_list,$ext_info);
		}
		session($cache_key, $cache_list);
		
		return implode('',$code_str);
	}
	

	/* 加密验证码 */
	private function authcode($str){
		$key = substr(md5($this->seKey), 5, 8);
		$str = substr(md5($str), 8, 10);
		return md5($key . $str);
	}
}
